package com.itheima.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/*
* Mapper代理抽取工具类
* */
public class MapperUtil {
    private MapperUtil(){}
    private static SqlSessionFactory factory ;
    static {
        try {
            //1、读取核心配置文件
            InputStream is =  Resources.getResourceAsStream("sqlConfig.xml");
            //2、构建SqlSessionFactory对象
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //定义一个方法获取SqlSession
    public static SqlSession getSession(){
        return factory.openSession();
    }

    //定义一个方法直接获取对应的mapper接口的代理对象
    public static <T> T getMapper(final Class<T> target){
        //1、获取session
        final SqlSession session = getSession();
        //2、获取代理对象（目标对象）
        final T mapper = session.getMapper(target);
        Object obj=Proxy.newProxyInstance(mapper.getClass().getClassLoader(), mapper.getClass().getInterfaces(), new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object obj=null;
                try{
                    obj=method.invoke(mapper,args);
                    session.commit();
                    session.close();
                }catch (Exception e){
                    e.printStackTrace();
                    //System.out.println("执行中出现了异常！！");
                }
                return obj;
            }
        });
        return (T) obj;

    }
}
